-- 發起電子郵件验证

local httparg    = require("shared.api.httparg")
local response   = require("shared.api.response")
local config     = require("config")
local tag        = httparg.tag()
local assertion  = httparg.assertion
local util                  = require "proxy.game.common.util"
local def                   = require "shared.api.def"
local httpclient            = require "shared.http.client"

local cjson = require "cjson.safe"
cjson.encode_max_depth(32)
cjson.decode_max_depth(32)


local ARGS = {
  tag.body('json'  , 'required'),

  account          =tag.json.account        ('string', assertion.non_empty_string()),
  recipient        =tag.json.recipient      ('string', assertion.non_empty_string()),
  verify_code      =tag.json.verify_code    ('string', assertion.non_empty_string()),
  sender           =tag.json.sender         ('string', 'required', assertion.non_empty_string()),
  subject          =tag.json.subject        ('string', 'required', assertion.non_empty_string()),
  body             =tag.json.body           ('string', 'required', assertion.non_empty_string()),
  charset          =tag.json.charset        ('string', 'required', assertion.non_empty_string()),
}

  local RESULT={}

do

  local headers               = ngx.req.get_headers()
  local query                 = nil
  local fill_response_header  = util.fill_response_header
  local GAAS_SHARED_REDIS     = config.GAAS_SHARED_REDIS
  local arg                   = ngx.req.get_uri_args()

  do

      headers['X-Forwarded-For'] = ngx.var.proxy_add_x_forwarded_for
  end


  local rmvLowKey="x-http-method-override"
  local rmvKey2="accept-encoding"
  for k,v in pairs(headers) do
      local low=string.lower(k)
      if low==rmvLowKey  or low==rmvKey2   then
          headers[k]=nil
      end
  end


  if ARGS.account==nil and ARGS.recipient==nil then
      RESULT.message       =def.ERROR_CODE.INVALID_ARGUMENT
      RESULT.description   =""
      ngx.status           =400
      response.success(RESULT)

  end

  if arg.CHECK_DUPLICATE_EMAIL then
     local location = config.ENV.DATAGATE_SERVICE .. "/account"
     local method   = "EXIST"

        if ARGS.recipient==nil then
            RESULT.message=def.ERROR_CODE.INVALID_ARGUMENT
            RESULT.description=""
            ngx.status =400
            response.success(RESULT)
        elseif ARGS.recipient~=nil then
            headers["Content-Type"]="text/plain"--text
            location=location.."?type=email"
            ngx.log(ngx.ERR,"exist location",location)
            local requestData=ARGS.recipient
            local resp, err = httpclient.new()
                                        :uri(location)
                                        :headers(headers)
                                        :query(query)
                                        :body(requestData)
                                        :send(method, 2000, nil)

            if err or (not resp) then
                ngx.status = 500
                ngx.say(err)
                ngx.exit(ngx.OK)
            end


            local is_match_content_type = util.is_match_content_type
            if not resp.body
                    or not resp.headers
                    or resp.status ~= 200
                    or not is_match_content_type(resp, 'application/json')  then

                ngx.status = resp.status
                fill_response_header(resp.headers)
                ngx.say(resp.body)
                ngx.exit(ngx.OK)
            end

            local respBody
            local get_content_decoder   = util.get_content_decoder
            local contentDecoder        = get_content_decoder(resp)
            if contentDecoder then
                respBody = contentDecoder.decode(resp.body)
            else
                ngx.status = 500
                ngx.say(err)
                ngx.exit(ngx.OK)
            end
            local found=respBody.found
            ngx.log(ngx.ERR,found)
            if found==true then
                RESULT.message="EMAIL ALREADY EXISTS"
                RESULT.description=""
                ngx.status =400
                response.success(RESULT)

            end

        end

    end


    local redis = require("shared.api.redis-adapter").new(GAAS_SHARED_REDIS)
    --nsq
    local producer = require "resty.nsq.producer"
    local GAAS_NSQ= config.GAAS_NSQ
    local prod = producer:new()


    local location = config.ENV.DATAGATE_SERVICE .. "/account"
    local method   = "PEEK"
    local bodyMap  = {}
     bodyMap.account=ARGS.account

    local requestData = cjson.encode(bodyMap)
    local recipient=""

    local ok, err = prod:connect(GAAS_NSQ.host,GAAS_NSQ.port)
    if not ok then
        ngx.say("failed to connect: ", err)
        return
    end


    local function generateVerifyCode()
        math.randomseed(tonumber(tostring(ngx.now()*1000):reverse():sub(1, 9)))
        local num =math.random(0,9)
        for i = 1, 5 do
            local randomNum=  math.random(0,9)
            num=string.format("%s%s",num,randomNum)
        end
        return num
    end

    ARGS.verify_code=generateVerifyCode()

    if ARGS.account then
        do
            local resp, err = httpclient.new()
                                        :uri(location)
                                        :headers(headers)
                                        :query(query)
                                        :body(requestData)
                                        :send(method, 2000, nil)

            if err or (not resp) then
                ngx.status = 500
                ngx.say(err)
                ngx.exit(ngx.OK)
            end

            local is_match_content_type = util.is_match_content_type
            if not resp.body
                    or not resp.headers
                    or resp.status ~= 200
                    or not is_match_content_type(resp, 'application/json')  then

                ngx.status = resp.status
                fill_response_header(resp.headers)
                ngx.say(resp.body)
                ngx.exit(ngx.OK)
            end

            local respBody
            local get_content_decoder   = util.get_content_decoder
            local contentDecoder        = get_content_decoder(resp)
            if contentDecoder then
                respBody = contentDecoder.decode(resp.body)
            else
                ngx.status = 500
                ngx.say(err)
                ngx.exit(ngx.OK)
            end
          recipient=respBody.email
        end
    end
    if ARGS.recipient then
        recipient=ARGS.recipient
    end


    local key=string.format("%s/verify_code/account:%s/email:%s","ocpgateway",ARGS.account,ARGS.recipient)
    ngx.log(ngx.ERR, key)
    --REDIS
     ok, err = redis:set(key, ARGS.verify_code)
    if not ok then
        ngx.say("failed to set key: ", err)
        return
    end
    ok, err =  redis:pexpire(key, 1000*600)
    if not ok then
        ngx.say("failed to pexpire key: ", err)
        return
    end



    local nsqMsg= {
        sender       =  ARGS.sender,
        recipient    =  recipient,
        subject      =  ARGS.subject,
        charset      =  "UTF-8"
    }

    nsqMsg.body=string.format(ARGS.body,ARGS.verify_code)
    local NSQ_MSG_BODY= cjson.encode(nsqMsg)
    ngx.log(ngx.ERR, NSQ_MSG_BODY)
    ok, err = prod:pub(GAAS_NSQ.topic,NSQ_MSG_BODY )
    if not ok then
        ngx.say("failed to pub: ", err)
        return
    end
    ok, err = prod:close()
    if not ok then
        ngx.say("failed to close: ", err)
        return
    end
end

    response.success(RESULT)



